package com.ys.chatserver.timer;

import com.alibaba.fastjson.JSONObject;
import com.eva.framework.utils.LoggerFactory;
import com.ys.chatserver.http.logic.LogicProcessor2;
import com.ys.chatserver.im.util.ChatServerUtils;
import com.ys.chatserver.im.util.MessageHelper;
import io.netty.channel.Channel;
import net.ys.mobileimsdk.server.processor.OnlineProcessor;

import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

public class OnlineTimer {

    public static void refreshOnlineStatus() {
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                try {
                    Vector<Vector<?>> vectors = LogicProcessor2.db.queryData("select user_uid from g_users where is_online is true and del_flag is false");
                    if (!vectors.isEmpty()) {
                        for (Vector<?> v : vectors) {
                            String userUid = v.get(0).toString();
                            Channel channel = OnlineProcessor.onlineSessions.get(userUid);
                            if (Objects.isNull(channel) || !channel.isActive()) {
                                LogicProcessor2.db.update("update g_users set latest_login_time2 = null,is_online = false where del_flag = 0 and user_uid=?"
                                        , new Object[]{userUid}, false);
                                sendOnLineMsg(userUid);
                            }
                        }
                    }
                } catch (Exception e) {
                    LoggerFactory.getLog().error(e.getMessage(), e);
                }
            }
        }, 10000, 6000);
    }


    private static void sendOnLineMsg(String userUid) throws Exception {
        Vector<Vector<?>> vectors = ChatServerUtils.getNotifyUserByUid(userUid);
        if (!vectors.isEmpty()) {
            int userType = ChatServerUtils.getUserType(userUid);
            for (Vector<?> userId : vectors) {
                if (userType == 1) {//设备
                    MessageHelper.sendDevOfflineMessage(userId.get(0).toString(), JSONObject.toJSONString(userId), null);
                } else {
                    MessageHelper.sendOfflineMessage(userId.get(0).toString(), JSONObject.toJSONString(userId), null);
                }
            }
        }
    }
}
